import * as qiniu from 'qiniu-js';
import { readFile } from "@tauri-apps/plugin-fs";
import { ApplicationCategory, Application } from '../types';
import { API_BASE_URL, getToken, request, uuid } from '../../utils';

export const qiniuGetUploadToken = async (): Promise<string> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/qiniu/upload_token`,
        method: 'GET',
        headers: {
            'Authorization': token
        },
    });
    const res = await response.text();
    console.log(res);
    return res;
}


export const qiniuGetUrl = async (keys: Array<string>): Promise<Array<string>> => {
    let token = getToken();
    let response = await request({
        url: `${API_BASE_URL}/qiniu/get_url`,
        method: 'POST',
        headers: {
            'Authorization': token
        },
        dataType: 'application/json',
        data: keys
    });
    const res: Array<string> = await response.json();
    console.log(res);
    return res;
}

export const qiniuUploadLocalFile = (file: string, filePath: string): Promise<{ hash: string, key: string } | null> => {
    const uploadConfig: qiniu.UploadConfig = {
        tokenProvider: async () => {
            // 线上应该使用服务端生成 token
            return await qiniuGetUploadToken();
        },
    };
    let ext = file.substring(file.lastIndexOf('.'));
    let filename = `${filePath}/${uuid()}${ext}`;

    return new Promise((resolve, reject) => {
        //读取文件内容
        readFile(file, {}).then((bytesContent) => {
            const fileData: qiniu.FileData = {
                type: 'array-buffer',
                filename: filename,
                data: bytesContent as any
            }
            let forceDirect = true;
            const newUploadTask = forceDirect
                ? qiniu.createDirectUploadTask(fileData, uploadConfig)
                : qiniu.createMultipartUploadV2Task(fileData, uploadConfig)

            newUploadTask.onProgress(progress => {
                //{size: 0, percent: 0.6666666666666666, details:{}
                console.log('progress', progress);
            })

            newUploadTask.onError(error => {
                console.log(error)
                reject(error);
            })

            newUploadTask.onComplete(resultStr => {
                //{"hash":"FhKOJmgsYAYDy7xG81nQuBHAdL40","key":"Square107x107Logo.png"}
                let result: { hash: string, key: string } = JSON.parse(resultStr);
                console.log('Complete', result, result.hash);
                resolve({ hash: result.hash, key: result.key });
            })
            newUploadTask.start()
        }).catch((err) => {
            reject(err);
        })
    });
}

